package com.ken.autocode.tools.generator.mainr;
import com.ken.autocode.tools.generator.config.EnvironmentConst;
import com.ken.autocode.tools.generator.config.MyConfig;
import com.ken.autocode.tools.generator.core.Gen;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;

//自动生成代码[jar版本]
public class JarCodeRun {
    public static void main(String[] args){
        try{
            String templateFolder =null;//模板文件根路径

            String[] tableNames =null;//需要生成的表

            //获取配置信息 start
            String property = System.getProperty("user.dir");
            System.out.println(property);
            //jar包状态下的运行
            String propFile = property+"\\"+"config\\basic.properties";
//          String propFile = property.substring(0,property.lastIndexOf("\\")+1)+"config\\basic.properties";

            Properties pro = new Properties();
            FileInputStream in = new FileInputStream(propFile);
            pro.load(in);
            in.close();

            templateFolder =new String(pro.getProperty("TEMPLATE_FOLDER").getBytes("ISO-8859-1"),"utf-8");

            //默认模板文件根目录
            if(templateFolder==null || "".equals(templateFolder.trim())){
                templateFolder = property+"\\"+"temp\\";
            }

            String tableInfo =new String(pro.getProperty("TABLENAMES").getBytes("ISO-8859-1"),"utf-8");
            System.out.println("tableInfo:"+tableInfo);

            if(tableInfo==null || "".equals(tableInfo.trim())){
                throw  new Error("配置文件未配置表名");
            }
            tableNames = tableInfo.split(",|，");

            Set<String> strings = pro.stringPropertyNames();

            MyConfig myConfig =new MyConfig();
            Class aClass = myConfig.getClass();
            String curValue="";

            Method declaredMethod =null;
            for(String key:strings){
                Field declaredField =null;
                try{
                    declaredField =   aClass.getDeclaredField(key);
                }catch (Exception ex){
//                    ex.printStackTrace();
                }
                //utf-8编码  解决中文乱码
                curValue =new String(pro.getProperty(key).getBytes("ISO-8859-1"),"utf-8");

                if(declaredField!=null){
                    declaredMethod = aClass.getDeclaredMethod("set" + key, String.class);
                    declaredMethod.setAccessible(true);
                    declaredMethod.invoke(myConfig,curValue);
                }
            }
            //获取配置信息 end

            Gen gen = new Gen();
            //初始化[模板路径没有 使用系统根目录下的路径]
            gen.init(templateFolder,EnvironmentConst.JAR);
            gen.setConfig(myConfig);
            //执行的方法
            gen.toDo(tableNames);

        }catch (Exception ex){
            ex.printStackTrace();
        }

    }



}
